import * as Cesium from "cesium";
import {Cartesian3, HeightReference, VerticalOrigin} from "cesium";
import * as turf from '@turf/turf'
import * as CesiumTools from "cesium-tools";


export let Entities:Array<Cesium.Entity> = [];

// export let LengthMeasureLabelEntities:Map<string, Array<Cesium.Entity>>;
export let LengthMeasureLabelEntities ={

};
export let AreaLabelEntities ={

};
export let HeightLabelEntities ={

};

export let AreaMeasureLabelEntities:Array<Cesium.Entity> = [];

export let FloatLabelEntities:Array<Cesium.Entity> = [];

export class Draw {
    viewer: any;
    customDataSource:any;
    myEntityCollection :any;
    private LengthUnit =  '米';
    constructor(view: any) {
        this.viewer = view;
        this.customDataSource = new Cesium.CustomDataSource("measureLabel");
        this.myEntityCollection = this.customDataSource.entities;
        this.viewer.dataSources.add(this.customDataSource);
    }
    // 校验和判断试图操作事件的状态的
    active: boolean = false;
    // 地图操作事件
    drawMapHandler: any;
    primitives: Array<any> = [];
    readonly PI:number = 3.1415926;
    private AreaUnit = '平方米';
    static UNIT = {
      DIS: {
          M: '米',
          KM: '千米',
      },
      AREA: {
          SM: '平方米',
          SKM: '平方公里',
          HECTARE: '公顷',
          ACRES: '亩'
      }
    };
    static TYPE = {
      POINT: 'point',
      POLYLINE: 'polyline',
      POLYGON: 'polygon',
      CIRCLE: 'circle',
      RECTANGLE: 'rectangle',
      Polyhedron: 'polyhedron'
    };

    // 激活地图操作事件
    AttachEvent() {
        if(!this.active) {
            this.drawMapHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas);
            this.active = true
        }
    }
    // 解绑地图操作事件
    DetachEvent() {
        if (this.active) {
            this.drawMapHandler.destroy();
            this.active = false
        }
    }

    /**
     * 通过这种方式获取的笛卡尔坐标不会偏移
     * @param screenCartesian
     */
    useGetCartesian3(screenCartesian: Cesium.Cartesian2){
        // // 获取相机射线
        // let ray = this.viewer.camera.getPickRay(screenCartesian);
        // // 射线与球体相交第一个点
        // let cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
        //
        // // 二维点转弧度
        // let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        // // 弧度转经纬度转笛卡尔坐标
        // let x = Cesium.Math.toDegrees(cartographic.longitude);
        // let y = Cesium.Math.toDegrees(cartographic.latitude);
        // let h = cartographic.height;
        // let cartesian3 = Cesium.Cartesian3.fromDegrees(x, y, h);
        // return cartesian3;

        // let picks = this.viewer.scene.pick(screenCartesian);
        // let cartesian = null;
        // let isOn3dtiles = false, isOnTerrain = false;
        // if (picks instanceof Cesium.Cesium3DTileFeature) { //模型上拾取
        //     isOn3dtiles = true;
        // }
        // // 3dtilset
        // if (isOn3dtiles) {
        //     cartesian = this.viewer.scene.pickPosition(screenCartesian);
        //     if (cartesian) {
        //         let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        //         if (cartographic.height < 0) cartographic.height = 0;
        //         let lon = Cesium.Math.toDegrees(cartographic.longitude)
        //           , lat = Cesium.Math.toDegrees(cartographic.latitude)
        //           , height = cartographic.height;//模型高度
        //         cartesian = this.transformWGS84ToCartesian({ lng: lon, lat: lat, alt: height })
        //     }
        // }
        // // 地形
        // if (!picks && !(this.viewer.terrainProvide instanceof Cesium.EllipsoidTerrainProvider)) {
        //     let ray = this.viewer.scene.camera.getPickRay(screenCartesian);
        //     if (!ray) return null;
        //     cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
        //     isOnTerrain = true
        // }
        // // 地球
        // if (!isOn3dtiles && !isOnTerrain) {
        //
        //     cartesian = this.viewer.scene.camera.pickEllipsoid(screenCartesian, this.viewer.scene.globe.ellipsoid);
        // }
        // if (cartesian) {
        //     let position = this.transformCartesianToWGS84(cartesian)
        //     if (position.alt < 0) {
        //         cartesian = this.transformWGS84ToCartesian(position, 0.1)
        //     }
        //     return cartesian;
        // }
        // return false;


        return CesiumTools.cartesian2To3(this.viewer, screenCartesian);
    }
    //坐标转换 笛卡尔转84
    transformCartesianToWGS84 (cartesian:Cesium.Cartesian3) {
        if (this.viewer && cartesian) {
            let ellipsoid = Cesium.Ellipsoid.WGS84
            let cartographic = ellipsoid.cartesianToCartographic(cartesian)
            return { lng: Cesium.Math.toDegrees(cartographic.longitude),
                lat: Cesium.Math.toDegrees(cartographic.latitude),
                alt: cartographic.height }
        }
    }
    //坐标转换 84转笛卡尔
    transformWGS84ToCartesian (position:any, alt?:number) {
        if (this.viewer) {
            return position ?
              Cesium.Cartesian3.fromDegrees(
      position.lng || position.lon,
                position.lat,
                position.alt = alt || position.alt,
                Cesium.Ellipsoid.WGS84
              ) : Cesium.Cartesian3.ZERO
        }
    }

    useDrawTerrainPointWithImg(name: string, resultCallBack: (id: string, type: string) => void, showName: boolean = false, showMeasure: boolean = false) {
        // 刷新一下操作事件
        this.DetachEvent();
        this.AttachEvent();
        let point: Cesium.Entity;
        let height;
        // 设置绘制点的地图点击事件
        this.drawMapHandler.setInputAction((evt: any) => {
            try{
                // 获取相机射线
                let ray = this.viewer.camera.getPickRay(evt.position);
                // 射线与球体相交第一个点
                let cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
                // 二维点转弧度
                let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
                // 弧度转经纬度转笛卡尔坐标
                let x = Cesium.Math.toDegrees(cartographic.longitude);
                let y = Cesium.Math.toDegrees(cartographic.latitude);
                height = cartographic.height;
                console.log("点击的", height);

                height = this.viewer.scene.sampleHeight(cartographic);
                console.log("计算的", height);

                let pickedObject = this.viewer.scene.pick(evt.position);
                if (this.viewer.scene.pickPositionSupported && Cesium.defined(pickedObject) && pickedObject.content) {
                    let cartesian = this.viewer.scene.pickPosition(evt.position);
                    if (Cesium.defined(cartesian)) {
                        let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
                        let lng = Cesium.Math.toDegrees(cartographic.longitude);
                        let lat = Cesium.Math.toDegrees(cartographic.latitude);
                        height = cartographic.height;//模型高度
                        console.log("拾取的", height);
                        console.log("最后高度", height);
                        let c = Cesium.Cartographic.fromDegrees(lng, lat, height);
                        let position = Cesium.Cartographic.toCartesian(c);
                        point = this.useCreatePointWithImg(position, name, showName);
                        // mapPosition={x:lng,y:lat,z:height}
                    }
                }else {
                    console.log("最后高度", height);
                    let c = Cesium.Cartographic.fromDegrees(x, y, height);
                    let position = Cesium.Cartographic.toCartesian(c);
                    point = this.useCreatePointWithImg(position, name, showName);

                }


                // point = this.useCreatePointWithImg(cartesian3, name, showName);
                // point = this.useCreatePointWithImg(position, name, showName);
                // this.primitives.push(point.id);
                Entities.push(point);
            } catch (e) {
                console.error(e);
                this.DetachEvent();
            } finally {
                this.DetachEvent();
                this.primitives.push(point.id);
                // let label = this.useCreateLabel(labelPosition)
                // Entities.push({id: point.id, point, nameLabel: label});
                // 返回创建点要素的id
                resultCallBack(point.id, 'point');
            }
        },Cesium.ScreenSpaceEventType.LEFT_CLICK)
    }
    useCreateTerrainPointWithImg(cartesian3: Cesium.Cartesian3, name: string, showName: boolean = false) {
        return this.viewer.entities.add({
            // 位置
            position: cartesian3,
            // name
            name: name,
            // point: {
            //     // 颜色
            //     color: Cesium.Color.fromCssColorString('#409eff'),
            //     // 贴地
            //     clampToGround: true,
            //     // 大小
            //     pixelSize: 10,
            //     // 边框颜色
            //     outlineColor: Cesium.Color.fromCssColorString('#409eff'),
            //     heightReference: HeightReference.CLAMP_TO_GROUND
            // },
            billboard: {
                scale: 0.1,
                image: "assets/images/locate.png",
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            }
        });
    }

    useDrawPointWithImg(name: string,earth:any, resultCallBack: (id: string, type: string) => void, showName: boolean = false, showMeasure: boolean = false) {
        // 刷新一下操作事件
        this.DetachEvent();
        this.AttachEvent();
        let point: Cesium.Entity;
        // 设置绘制点的地图点击事件
        this.drawMapHandler.setInputAction((evt: any) => {
            try{
                // let cartesian3 = this.useGetCartesian3(evt.position);
                console.log(earth,99)
                let cartesian3:Cesium.Cartesian3;
                const scene = earth.viewer.scene;
                if(scene.mode !== Cesium.SceneMode.MORPHING){
                  let pickObj = scene.pick(evt.position);
                  if(scene.pickPositionSupported && Cesium.defined(pickObj) && pickObj.primitive){
            
                    let cartesian = earth.viewer.scene.pickPosition(evt.position);
                      if(Cesium.defined(cartesian)){
                        let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
                        let lng = Cesium.Math.toDegrees(cartographic.longitude);
                        let lat = Cesium.Math.toDegrees(cartographic.latitude);
                        let height = cartographic.height;
                        cartesian3 = Cesium.Cartesian3.fromDegrees(lng, lat, height);
                      }
                  } else if(scene.pickPositionSupported) {
                    let cartesian = earth.viewer.scene.pickPosition(evt.position);
                    if(Cesium.defined(cartesian)){
                      let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
                      let lng = Cesium.Math.toDegrees(cartographic.longitude);
                      let lat = Cesium.Math.toDegrees(cartographic.latitude);
                      let height = cartographic.height;
                      cartesian3 = Cesium.Cartesian3.fromDegrees(lng, lat, height);
                }
              }
                }
                // @ts-ignore
                point = this.useCreatePointWithImg(cartesian3, name, showName);
                // this.primitives.push(point.id);
                Entities.push(point);
            } catch (e) {
                console.error(e);
                this.DetachEvent();
            } finally {
                this.DetachEvent();
                this.primitives.push(point.id);
                // let label = this.useCreateLabel(labelPosition)
                // Entities.push({id: point.id, point, nameLabel: label});
                // 返回创建点要素的id
                resultCallBack(point.id, 'point');
            }
        },Cesium.ScreenSpaceEventType.LEFT_CLICK)
    }
    useCreatePointWithImg(cartesian3: Cesium.Cartesian3, name: string, showName: boolean = false) {
        return this.viewer.entities.add({
            // 位置
            position: cartesian3,
            // name
            name: name,
            // point: {
            //     // 颜色
            //     color: Cesium.Color.fromCssColorString('#409eff'),
            //     // 贴地
            //     clampToGround: true,
            //     // 大小
            //     pixelSize: 10,
            //     // 边框颜色
            //     outlineColor: Cesium.Color.fromCssColorString('#409eff'),
            //     heightReference: HeightReference.CLAMP_TO_GROUND
            // },
            billboard: {
                scale: 0.1,
                image: "assets/images/locate.png",
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                heightReference: Cesium.HeightReference.NONE
            }
        });
    }

    /**
     * @description 绘制点的事件 绘制一个点 回调事件可以用来等点要素绘制完成之后调用 返回点要素
     * @param resultCallBack
     */
    useDrawPoint(name: string, resultCallBack: (id: string, type: string) => void, showName: boolean, showMeasure: boolean = false) {
        // 刷新一下操作事件
        this.DetachEvent();
        this.AttachEvent();
        let point: Cesium.Entity;
        // 设置绘制点的地图点击事件
        this.drawMapHandler.setInputAction((evt: any) => {
            try{
                // // 屏幕坐标转世界坐标——关键点
                // let ray = this.viewer.camera.getPickRay(evt.position);
                // let cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
                // // 将笛卡尔坐标转换为地理坐标
                // let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
                // // 将弧度转为度的十进制度表示
                // let lon = Cesium.Math.toDegrees(cartographic.longitude);
                // let lat = Cesium.Math.toDegrees(cartographic.latitude);
                // // 获取海拔高度
                // let height1 = this.viewer.scene.globe.getHeight(cartographic);
                // let pointInfo =  {longitude:lon,latitude:lat,height:height1};
                // let cartesian3 = Cesium.Cartesian3.fromDegrees(pointInfo.longitude,pointInfo.latitude,pointInfo.height);

                let cartesian3 = this.useGetCartesian3(evt.position);
                point = this.useCreatePoint(cartesian3, name, showName);
                // this.primitives.push(point.id);
                Entities.push(point);
            } catch (e) {
                console.error(e);
                this.DetachEvent();
            } finally {
                this.DetachEvent();
                this.primitives.push(point.id);
                // let label = this.useCreateLabel(labelPosition)
                // Entities.push({id: point.id, point, nameLabel: label});
                // 返回创建点要素的id
                resultCallBack(point.id, 'point');
            }
        },Cesium.ScreenSpaceEventType.LEFT_CLICK)
    }

    /**
     * @description 输入一个点位以及name 创建并返回一个点要素
     * @param cartesian3
     * @param name
     * @param showName
     */
    private useCreatePoint(cartesian3: Cesium.Cartesian3, name: string, showName: boolean) {
        return this.viewer.entities.add({
            // 位置
            position: cartesian3,
            // name
            name: name,
            point: {
                // 颜色
                color: Cesium.Color.fromCssColorString('#409eff'),
                // 贴地
                clampToGround: true,
                // 大小
                pixelSize: 10,
                // 边框颜色
                outlineColor: Cesium.Color.fromCssColorString('#409eff'),
                // outlineColor: Cesium.Color.fromCssColorString('#EB341F'),
                outlineWidth: 1,
                heightReference: HeightReference.CLAMP_TO_GROUND,
                disableDepthTestDistance:Number.POSITIVE_INFINITY
            },
            label: new Cesium.LabelGraphics({
                text: name,
                font: '24px MicroSoft YaHei',
                show: showName,
                fillColor: Cesium.Color.fromCssColorString('white'),
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                scaleByDistance: new Cesium.NearFarScalar(10000, 1, 100000, 0),
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                verticalOrigin: VerticalOrigin.TOP,
                pixelOffset: new Cesium.Cartesian2(0, 12)
            })
        });
    }

    /**
     * @description 线要素的绘制事件 输入要素name 以及回调函数 其中id 接收创建线要素的id
     * @param name
     * @param resultCallBack
     * @param showName
     * @param showMeasure
     * @param lengthUnit
     */
    useDrawPolyline(name: string, resultCallBack: (id: string, type: string) => void, showName: boolean, showMeasure: boolean, lengthUnit: string = '米') {
        // 刷新操作事件
        this.DetachEvent();
        this.AttachEvent();
        // 创建一个变量用来存储线要素的点位
        let polylinePositions: Array<any> = [];
        let floatLabel: Cesium.Entity;
        let lastCartesian: Cesium.Cartesian3;
        // 总长度
        let distance = 0;
        // 线要素
        let polyline:any = null;
        // 设置地图操作事件
        // 左键点击
        this.drawMapHandler.setInputAction((evt: any) => {
            // // 拾取笛卡尔坐标
            // let cartesian3 = this.viewer.scene.pickPosition(evt.position);
            // if (!cartesian3) {
            //     let ray = this.viewer.camera.getPickRay(evt.position);
            //     cartesian3 = this.viewer.scene.globe.pick(ray, this.viewer.scene);
            // }
            // // 拾取不到 返回异常
            // if (!cartesian3) return {error: '拾取点位异常'};
            let cartesian3 = this.useGetCartesian3(evt.position);
            // 第一次点击的时候
            if (polylinePositions.length === 0) {
                polylinePositions.push(cartesian3);
                polylinePositions.push(cartesian3.clone());
                lastCartesian = cartesian3;
                // 浮动点的量算值
                floatLabel = this.useCreateLabel(cartesian3, Draw.TYPE.POINT, true, true);
            } else {
                polylinePositions.push(cartesian3);
                let textLabel = this.useCreateLabel(cartesian3, Draw.TYPE.POINT, showMeasure);
                //存储标签要素
                this.useSaveTextLabel(polyline.id, textLabel, Draw.TYPE.POLYLINE);
                distance += this.useMeasureDistance(lastCartesian, cartesian3);
                textLabel.label.text = this.useFormatUnit(distance, lengthUnit);
                textLabel.description = distance;
                lastCartesian = cartesian3;
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        // 坐标移动
        this.drawMapHandler.setInputAction((evt: any) => {
            // let cartesian3 = this.viewer.scene.pickPosition(evt.endPosition);
            // if (!cartesian3) {
            //     let ray = this.viewer.camera.getPickRay(evt.endPosition);
            //     cartesian3 = this.viewer.scene.globe.pick(ray, this.viewer.scene);
            // }
            // if (!cartesian3) return {error: '拾取点位异常'};
            let cartesian3 = this.useGetCartesian3(evt.endPosition);
            if (polylinePositions.length >= 2) {
                if (!Cesium.defined(polyline)) {
                    polyline = this.useCreateLine(polylinePositions, name, showName, showMeasure);
                    // 存储id
                    // this.primitives.push(polyline.id);
                    Entities.push(polyline);

                } else {
                    polylinePositions.pop();
                    polylinePositions.push(cartesian3);
                    // @ts-ignore
                    floatLabel.label.text = this.useFormatUnit(distance + this.useMeasureDistance(lastCartesian, cartesian3), lengthUnit);
                    // @ts-ignore
                    floatLabel.description = distance + this.useMeasureDistance(lastCartesian, cartesian3);
                    // @ts-ignore
                    floatLabel.position.setValue(cartesian3);
                }
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        // 双击
        this.drawMapHandler.setInputAction((evt: any) => {
            this.DetachEvent();
            resultCallBack(polyline.id, 'polyline');
            //存储标签要素
            this.useSaveTextLabel(polyline.id, floatLabel, Draw.TYPE.POLYLINE);
            // floatLabel.show = false;
            // this.viewer.entities.remove(floatLabel);

        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    }

    /**
     * 实时绘制线要素
     * @param polylinePositions
     * @param name
     */
    private useCreateLine(polylinePositions: any[], name: string, showName: boolean = false, showMeasure: boolean = false) {
        return this.viewer.entities.add({
            name: name,
            position: new Cesium.CallbackProperty(function () {
                return Cesium.BoundingSphere.fromPoints(polylinePositions).center;
            }, false),
            polyline: new Cesium.PolylineGraphics({
                positions: new Cesium.CallbackProperty(function () {
                    return polylinePositions
                }, false),
                show: true,
                material: Cesium.Color.fromCssColorString('#409eff'),
                width: 5,
                clampToGround: true,
                classificationType: Cesium.ClassificationType.BOTH,
            }),
            label: new Cesium.LabelGraphics({
                text: name,
                font: '24px MicroSoft YaHei',
                fillColor: Cesium.Color.fromCssColorString('white'),
                show: showName,
                // 贴地
                heightReference: HeightReference.CLAMP_TO_GROUND,
                scaleByDistance: new Cesium.NearFarScalar(10000, 1, 100000, 0),
                // 地形遮挡
                disableDepthTestDistance: Number.POSITIVE_INFINITY
            })
            // polyline: {
            //     positions: new Cesium.CallbackProperty(function () {
            //         return polylinePositions
            //     }, false),
            //     show: true,
            //     // disableDepthTestDistance: Number.POSITIVE_INFINITY,
            //     // material: Cesium.Color.LIGHTSKYBLUE,
            //     material: Cesium.Color.fromCssColorString('yellow'),
            //     width: 8,
            //     clampToGround: true,
            //     classificationType: Cesium.ClassificationType.BOTH,
            //     cornerType: Cesium.CornerType.MITERED
            // }
        })
    }

    /**
     * @description 绘制面要素
     * @param name
     * @param resultCallBack
     */
    useDrawPolygon(name: string, resultCallBack: (id: string, type: string) => void, showName: boolean, showMeasure: boolean, areaUnit:string = '平方米') {
        // 重新绑定事件
        this.DetachEvent();
        this.AttachEvent();
        // 创建一个变量用来存储面要素的点位
        let polygonPositions: Array<Cartesian3> = [];
        // 创建一个存储外边框线要素的点位
        // let polylinePositions: Array<Cartesian3> = [];
        // 用于存储创建的面要素
        let polygon: Cesium.Entity;
        // let polyline: Cesium.Entity;

        let measureLabel: Cesium.Entity;
        // 设置左击事件
        this.drawMapHandler.setInputAction((evt: any) => {
            let cartesian3 = this.useGetCartesian3(evt.position);
            // 开始绘制面要素

            if (polygonPositions.length === 1) {
                // polygonPositions.push(cartesian3.clone());
                polygonPositions.push(cartesian3);
            } else {
                polygonPositions.push(cartesian3);
                // polylinePositions.splice(polylinePositions.length - 1, 0, cartesian3);
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        // 鼠标移动事件
        this.drawMapHandler.setInputAction((evt: any) => {
            try {
                let cartesian3 = this.useGetCartesian3(evt.endPosition);
                // if (polygonPositions.length === 2)  {
                //     if (!Cesium.defined((polyline))){
                //         polyline = this.useCreateLine(polylinePositions, '');
                //         Entities.push(polyline);
                //         // 移动时候 外边框线要素
                //         polylinePositions.splice(polylinePositions.length - 1, 0, cartesian3);
                //     }
                // }
                // 是否初始创建面要素
                // if (polygonPositions.length === 3) {
                if (polygonPositions.length === 2) {
                    if (!Cesium.defined(polygon)) {
                        polygon = this.useCreatePolygon(polygonPositions, name, showName, showMeasure);


                        // this.primitives.push(polygon.id);
                        Entities.push(polygon);
                    }
                }
                polygonPositions.pop();
                polygonPositions.push(cartesian3);


                // 面要素是否存在
                if (polygon) {
                }
            } catch (e) {
                console.error(e);
                this.DetachEvent();
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        // 右击事件
        this.drawMapHandler.setInputAction((evt: any) => {
            let cartesian3s = polygonPositions;
            cartesian3s = [...cartesian3s, cartesian3s[0]];
            measureLabel = this.useCreateLabel(polygonPositions, Draw.TYPE.POLYGON, showMeasure);
            this.useSaveTextLabel(polygon.id, measureLabel, Draw.TYPE.POLYGON);
            let value = this.useGetArea(cartesian3s);
            // @ts-ignore
            measureLabel.description = value + '';
            let res = this.useFormatUnit(value, areaUnit);
            // @ts-ignore
            measureLabel.label.text = res;


            resultCallBack(polygon.id, 'polygon');
            this.DetachEvent();
            // let measureLabel = this.useCreateLabel(polygonPositions, 'polygon', showMeasure);
            // this.useSaveTextLabel(polygon.id, measureLabel, Draw.TYPE.POLYGON);
            // measureLabel.label.text = this.useFormatUnit(measureLabel.description, areaUnit);

            // AreaMeasureLabelEntities.push(measureLabel);
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    }

    private useCreatePolygon(polygonPositions: any[], name: string, showName: boolean, showMeasure: boolean) {
        return this.viewer.entities.add({
            name: name,
            position: new Cesium.CallbackProperty(function () {
                return Cesium.BoundingSphere.fromPoints(polygonPositions).center;
            }, false),
            polyline: new Cesium.PolylineGraphics({
                positions: new Cesium.CallbackProperty(function () {
                    let polylinePositions = [...polygonPositions, polygonPositions[0]];
                    return polylinePositions;
                }, false),
                show: true,
                material: Cesium.Color.fromCssColorString('#409eff'),
                width: 5,
                clampToGround: true,
                classificationType: Cesium.ClassificationType.BOTH,
            }),
            polygon: new Cesium.PolygonGraphics({
                hierarchy: new Cesium.CallbackProperty(function () {
                    return new Cesium.PolygonHierarchy(polygonPositions)
                }, false),
                // clampToGround: true,
                material: Cesium.Color.WHITESMOKE.withAlpha(0.3),
                // disableDepthTestDistance: Number.POSITIVE_INFINITY,
                show: true,
                fill: true,
                outline: true,
                // outlineColor: new Cesium.Color(64, 133, 235),
                // outlineColor: Cesium.Color.YELLOW,
                // outlineColor: new Cesium.Color.fromCssColorString(outlineColor),
                outlineWidth: 1
            }),
            label: new Cesium.LabelGraphics({
                text: name,
                show: showName,
                font: '24px MicroSoft YaHei',
                fillColor: Cesium.Color.fromCssColorString('white'),
                scaleByDistance: new Cesium.NearFarScalar(10000, 1, 100000, 0),
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            })
        });
    }

    private useCreatePolyhedron(polygonPositions: any[], name: string, showName: boolean, showMeasure: boolean) {
        // console.log(polygonPositions)
        return this.viewer.entities.add({
            name: name,
            position: new Cesium.CallbackProperty(function () {
                return Cesium.BoundingSphere.fromPoints(polygonPositions).center;
            }, false),
            polyline: new Cesium.PolylineGraphics({
                positions: new Cesium.CallbackProperty(function () {
                    let polylinePositions = [...polygonPositions, polygonPositions[0]];
                    return polylinePositions;
                }, false),
                show: true,
                material: Cesium.Color.fromCssColorString('#409eff'),
                width: 5,
                clampToGround: true,
                classificationType: Cesium.ClassificationType.BOTH,
            }),
            polygon: new Cesium.PolygonGraphics({
                hierarchy: new Cesium.CallbackProperty(function () {
                    return new Cesium.PolygonHierarchy(polygonPositions)
                }, false),
                // hierarchy:polygonPositions,
                // hierarchy:new Cesium.PolygonHierarchy(polygonPositions),
                // clampToGround: true,
                material: Cesium.Color.WHITESMOKE.withAlpha(0.3),
                outline: true,
                // disableDepthTestDistance: Number.POSITIVE_INFINITY,
                // show: true,
                // fill: true,
                // outline: true,
                // material: Cesium.Color.PURPLE,
                // outlineColor: Cesium.Color.fromCssColorString('#409eff'),
                // outlineColor: Cesium.Color.GREEN,
                // arcType: Cesium.ArcType.RHUMB,
                // outlineColor: new Cesium.Color(64, 133, 235),
                // outlineColor: Cesium.Color.YELLOW,
                // outlineColor: new Cesium.Color.fromCssColorString(outlineColor),
                outlineWidth: 1,
                arcType: Cesium.ArcType.RHUMB,
                closeBottom:true,
                extrudedHeight: 10,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                // extrudedHeightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
                // height:0,
                // extrudedHeight: 0,

            }),
            label: new Cesium.LabelGraphics({
                text: name,
                show: showName,
                font: '24px MicroSoft YaHei',
                fillColor: Cesium.Color.fromCssColorString('white'),
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                scaleByDistance: new Cesium.NearFarScalar(10000, 1, 100000, 0),
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            })
        });
    }

    useDrawRectangle(name: string, resultCallBack: (id: string, type: string) => void, showName: boolean, showMeasure: boolean, areaUnit:string = '平方米') {
        this.DetachEvent();
        this.AttachEvent();
        // @ts-ignore
        let rectangle;
        let westSouthEastNorth:any[] = [];
        let measureLabel: Cesium.Entity;
        // TODO 浮动坐标显示量算 量算与名称显示关闭的开关 单位换算 名称改变
        this.drawMapHandler.setInputAction((click: any) => {
                let cartesian3 = this.useGetCartesian3(click.position);
                /**笛卡尔转弧度坐标 */
                let cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
                /**点击位置经度 */
                let lng1 = Cesium.Math.toDegrees(cartographic.longitude);
                /**点击位置维度 */
                let lat1 = Cesium.Math.toDegrees(cartographic.latitude);
                /**边框坐标 */
                westSouthEastNorth = [lng1, lat1];
                if (westSouthEastNorth) {
                    this.drawMapHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
                }
                // rectangle = drawUtil.dynamicDrawRectangleByArr(westSouthEastNorth, showName);
                rectangle = this.useCreateRectangle(westSouthEastNorth, name, showName);

                measureLabel = this.useCreateLabel(westSouthEastNorth, Draw.TYPE.RECTANGLE, showMeasure);
                // @ts-ignore
                this.useSaveTextLabel(rectangle.id, measureLabel, Draw.TYPE.POLYGON);

                Entities.push(rectangle);
                let b = true;
                this.drawMapHandler.setInputAction((move:any) => {
                    let cartesian = this.useGetCartesian3(move.endPosition);
                    let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
                    let lng = Cesium.Math.toDegrees(cartographic.longitude);
                    let lat = Cesium.Math.toDegrees(cartographic.latitude);
                    if (b) {
                        b = false;
                        westSouthEastNorth.push(lng1);
                        westSouthEastNorth.push(lat);
                        westSouthEastNorth.push(lng);
                        westSouthEastNorth.push(lat);
                        westSouthEastNorth.push(lng);
                        westSouthEastNorth.push(lat1);
                        westSouthEastNorth.push(lng1);
                        westSouthEastNorth.push(lat1);
                    } else {
                        westSouthEastNorth.splice(3 , 4, lat, lng, lat, lng);
                    }
                    // @ts-ignore
                    if(rectangle) {
                        let cartesian3s = Cesium.Cartesian3.fromDegreesArray(westSouthEastNorth);
                        cartesian3s = [...cartesian3s, cartesian3s[0]]
                        // @ts-ignore
                        measureLabel.description = this.useGetArea(cartesian3s);
                        // @ts-ignore
                        measureLabel.label.text = this.useFormatUnit(measureLabel.description, areaUnit);
                    }
                }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
            },Cesium.ScreenSpaceEventType.LEFT_CLICK);
        this.drawMapHandler.setInputAction((click:any) => {
            this.DetachEvent();
            // @ts-ignore
            resultCallBack(rectangle.id, 'rectangle');
            // measureLabel = this.useCreateLabel(westSouthEastNorth, Draw.TYPE.RECTANGLE, showMeasure);
            // // @ts-ignore
            // this.useSaveTextLabel(rectangle.id, measureLabel, Draw.TYPE.POLYGON);
            // @ts-ignore
            // measureLabel.label.text = this.useFormatUnit(measureLabel.description, areaUnit);
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    }

    private useCreateRectangle(positions: any[], name: string, showName: boolean) {
        return this.viewer.entities.add({
            name: name,
            position: new Cesium.CallbackProperty(function () {
                // @ts-ignore
                return Cesium.BoundingSphere.fromPoints(Cesium.Cartesian3.fromDegreesArray(positions)).center;
            }, false),
            polygon: {
                hierarchy: new Cesium.CallbackProperty(function () {
                    return {
                        positions: Cesium.Cartesian3.fromDegreesArray(positions)
                    }
                }, false),
                // 填充的颜色，withAlpha透明度
                material: Cesium.Color.WHITESMOKE.withAlpha(0.3),
                // 是否显示
                show: true
            },
            polyline: {
                positions: new Cesium.CallbackProperty(function () { return Cesium.Cartesian3.fromDegreesArray(positions) }, false),
                material: Cesium.Color.fromCssColorString("#409eff"),
                width: 5,
                clampToGround: true,
                zIndex: 1
            },
            label: {
                text: name,
                show: showName,
                font: '24px MicroSoft YaHei',
                fillColor: Cesium.Color.fromCssColorString('white'),
                scaleByDistance: new Cesium.NearFarScalar(10000, 1, 100000, 0),
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                // heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND
            }
        });
        // return this.viewer.entities.add({
        //     name: name,
        //     position: new Cesium.CallbackProperty(function () {
        //         return Cesium.Cartesian3.fromDegrees((position[0] + position[2]) / 2, (position[1] + position[3]) / 2)
        //     }, false),
        //     rectangle: {
        //         coordinates: Cesium.Rectangle.fromDegrees(position[0], position[1], position[2], position[3]),
        //         material: Cesium.Color.GREEN.withAlpha(0.5),
        //         // rotation: Cesium.Math.toRadians(45),
        //         extrudedHeight: 0,
        //         height: 0,
        //     },
        //     label: new Cesium.LabelGraphics({
        //         text: name,
        //         show: false
        //     })
        // })
    }

    useDrawCircle(name: string, resultCallBack: (id: string, type: string) => void, showName: boolean, showMeasure: boolean, areaUnit:string = '平方米') {
        this.DetachEvent();
        this.AttachEvent();
        let radius:number = 1;
        let circle: Cesium.Entity;
        let cartesian3x: Cartesian3;
        let cartesian3y: Cartesian3;
        let circlePositions: Array<Cartesian3>;
        let measureLabel: Cesium.Entity;
        this.drawMapHandler.setInputAction((evt: any) => {
            try {
                let cartesian3 = this.useGetCartesian3(evt.position);
                // 拾取点位异常
                if (!cartesian3) return {error: '拾取点位异常'};
                let cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
                // 弧度转经纬度转笛卡尔坐标
                let x = Cesium.Math.toDegrees(cartographic.longitude);
                let y = Cesium.Math.toDegrees(cartographic.latitude);
                let h = cartographic.height;
                let center = [x, y];
                let options = {steps: 10, units: 'meters', properties: {foo: 'bar'}};

                // @ts-ignore
                let circleFeatures = turf.circle(center, radius, options);
                let coordinates = circleFeatures.geometry.coordinates[0];

                let degressArr: Array<any> = [];
                coordinates.forEach(item => {
                    degressArr.push(item[0]);
                    degressArr.push(item[1]);
                });
                circlePositions = [...Cesium.Cartesian3.fromDegreesArray(degressArr)];
                circle = this.useCreateLingStringCircle(circlePositions, radius, name, showName);

                // measureLabel = this.useCreateLabel([cartesian3x, cartesian3y], Draw.TYPE.CIRCLE, showMeasure);
                let p = Cesium.BoundingSphere.fromPoints(circlePositions).center;
                measureLabel = this.useCreateLabel([p], Draw.TYPE.CIRCLE, showMeasure);
                this.useSaveTextLabel(circle.id, measureLabel, Draw.TYPE.POLYGON);
                // measureLabel = this.useCreateLabel([cartesian3x, cartesian3y], Draw.TYPE.CIRCLE, showMeasure);
                // this.useSaveTextLabel(circle.id, measureLabel, Draw.TYPE.POLYGON);

                // this.primitives.push(circle.id);
                Entities.push(circle);
                if (cartesian3) {
                    this.drawMapHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
                }
                this.drawMapHandler.setInputAction((evt: any) => {
                    // // 拾取点位异常
                    let cartesian3_end = this.useGetCartesian3(evt.endPosition);
                    if (!cartesian3_end) return {error: '拾取点位异常'};
                    radius = Number(Cesium.Cartesian3.distance(cartesian3, cartesian3_end));
                    options = {steps: 360, units: 'meters', properties: {foo: 'bar'}};

                    // @ts-ignore
                    circleFeatures = turf.circle(center, radius, options);
                    coordinates = circleFeatures.geometry.coordinates[0];

                    degressArr = [];
                    coordinates.forEach(item => {
                        degressArr.push(item[0]);
                        degressArr.push(item[1]);
                    });
                    // circlePositions 为线要素的笛卡尔坐标数组
                    Cesium.Cartesian3.fromDegreesArray(degressArr).forEach((item,index) => {
                        circlePositions[index] = item
                    });
                    // 下面方式都是是不行的
                    // circlePositions = Cesium.Cartesian3.fromDegreesArray(degressArr);
                    // circlePositions = [...Cesium.Cartesian3.fromDegreesArray(degressArr)];

                    cartesian3x = cartesian3;
                    cartesian3y = cartesian3_end;

                    if(circle) {
                        // @ts-ignore
                        measureLabel.description = this.useGetCircleArea([cartesian3x, cartesian3y]);
                        // @ts-ignore
                        measureLabel.label.text = this.useFormatUnit(measureLabel.description, areaUnit)
                    }

                }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
            } catch (e) {
                console.error(e);
                this.DetachEvent();
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        this.drawMapHandler.setInputAction((evt: any) => {
            this.DetachEvent();
            resultCallBack(circle.id, 'circle');
            // measureLabel = this.useCreateLabel([cartesian3x, cartesian3y], Draw.TYPE.CIRCLE, showMeasure);
            // // @ts-ignore
            // this.useSaveTextLabel(circle.id, measureLabel, Draw.TYPE.POLYGON);
            // @ts-ignore
            // measureLabel.label.text = this.useFormatUnit(measureLabel.description, areaUnit);

            // AreaMeasureLabelEntities.push(measureLabel)
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)


        // this.DetachEvent();
        // this.AttachEvent();
        // let radius:number = 1;
        // let circle: Cesium.Entity;
        // let cartesian3x: Cartesian3;
        // let cartesian3y: Cartesian3;
        // this.drawMapHandler.setInputAction((evt: any) => {
        //     try {
        //         // // 拾取笛卡尔坐标
        //         // let cartesian3 = this.viewer.scene.pickPosition(evt.position);
        //         // if (!cartesian3) {
        //         //     let ray = this.viewer.camera.getPickRay(evt.position);
        //         //     cartesian3 = this.viewer.scene.globe.pick(ray, this.viewer.scene);
        //         // }
        //         let cartesian3 = this.useGetCartesian3(evt.position);
        //         // 拾取点位异常
        //         if (!cartesian3) return {error: '拾取点位异常'};
        //         circle = this.useCreateCircle(cartesian3, radius, name, showName);
        //         // this.primitives.push(circle.id);
        //         Entities.push(circle);
        //
        //         // @ts-ignore
        //         circle.ellipse.semiMajorAxis = new Cesium.CallbackProperty(function () { return radius }, false);
        //         // @ts-ignore
        //         circle.ellipse.semiMinorAxis = new Cesium.CallbackProperty(function () { return radius }, false);
        //
        //         if (cartesian3) {
        //             this.drawMapHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
        //         }
        //         this.drawMapHandler.setInputAction((evt: any) => {
        //             // let cartesian3_end = this.viewer.scene.pickPosition(evt.endPosition);
        //             // if (!cartesian3_end) {
        //             //     let ray = this.viewer.camera.getPickRay(evt.endPosition);
        //             //     cartesian3_end = this.viewer.scene.globe.pick(ray, this.viewer.scene);
        //             // }
        //             // // 拾取点位异常
        //             let cartesian3_end = this.useGetCartesian3(evt.endPosition);
        //             if (!cartesian3_end) return {error: '拾取点位异常'};
        //             radius = Number(Cesium.Cartesian3.distance(cartesian3, cartesian3_end));
        //             cartesian3x = cartesian3;
        //             cartesian3y = cartesian3_end;
        //
        //         }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
        //     } catch (e) {
        //         console.error(e);
        //         this.DetachEvent();
        //     }
        // }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        // this.drawMapHandler.setInputAction((evt: any) => {
        //     this.DetachEvent();
        //     resultCallBack(circle.id, 'circle');
        //     let measureLabel = this.useCreateLabel([cartesian3x, cartesian3y], 'circle', showMeasure);
        //     // @ts-ignore
        //     this.useSaveTextLabel(circle.id, measureLabel, Draw.TYPE.POLYGON);
        //     measureLabel.label.text = this.useFormatUnit(measureLabel.description, areaUnit);
        //     // AreaMeasureLabelEntities.push(measureLabel)
        // }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    }

    private useCreateCircle(cartesian3: Cesium.Cartesian3, radius:number, name: string, showName: boolean) {
        return this.viewer.entities.add({
            name: name,
            position: cartesian3,
            // ellipse: {
            //     outline: true,
            //     // clampToGround: true,
            //     material: Cesium.Color.fromCssColorString("#409eff").withAlpha(.2),
            //     outlineColor: Cesium.Color.fromCssColorString("#409eff"),
            //     outlineWidth: 4,
            // },
            ellipse: {
                // semiMajorAxis: new Cesium.CallbackProperty(function () { return radius }, false),
                // semiMinorAxis: new Cesium.CallbackProperty(function () { return radius }, false),
                material: Cesium.Color.fromCssColorString("#409eff").withAlpha(0.2),
                outline: true,
            },
            label: new Cesium.LabelGraphics({
                text: name,
                show: showName
            })
        })
    }

    private useCreateLingStringCircle(positions: Array<Cartesian3>, radius: number, name: string, showName: boolean) {
        return this.viewer.entities.add({
            name: name,
            position: new Cesium.CallbackProperty(function () {
                return Cesium.BoundingSphere.fromPoints(positions).center;
            }, false),
            polyline: new Cesium.PolylineGraphics({
                positions: new Cesium.CallbackProperty(function () {
                    let polylinePositions = [...positions, positions[0]];
                    return polylinePositions;
                }, false),
                show: true,
                material: Cesium.Color.fromCssColorString('#409eff'),
                width: 5,
                clampToGround: true,
                classificationType: Cesium.ClassificationType.BOTH,
            }),
            polygon: new Cesium.PolygonGraphics({
                hierarchy: new Cesium.CallbackProperty(function () {
                    return new Cesium.PolygonHierarchy(positions)
                }, false),
                // clampToGround: true,
                material: Cesium.Color.WHITESMOKE.withAlpha(0.3),
                // disableDepthTestDistance: Number.POSITIVE_INFINITY,
                show: true,
                fill: true,
                outline: true,
                // outlineColor: new Cesium.Color(64, 133, 235),
                // outlineColor: Cesium.Color.YELLOW,
                // outlineColor: new Cesium.Color.fromCssColorString(outlineColor),
                outlineWidth: 1
            }),
            label: new Cesium.LabelGraphics({
                text: name,
                show: showName,
                font: '24px MicroSoft YaHei',
                fillColor: Cesium.Color.fromCssColorString('white'),
                // 地形遮挡
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                scaleByDistance: new Cesium.NearFarScalar(10000, 1, 100000, 0),
                // 贴地
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            })
        });
    }

    useDrawPolyhedron(name: string, resultCallBack: (id: string, type: string) => void, showName: boolean, showMeasure: boolean, areaUnit:string='平方米') {
        // 重新绑定事件
        this.DetachEvent();
        this.AttachEvent();
        // 创建一个变量用来存储面要素的点位
        let polygonPositions: Array<any> = [];
        // 用于存储创建的面要素
        let polygon: Cesium.Entity;
        // 设置左击事件
        this.drawMapHandler.setInputAction((evt: any) => {
            try {
                // // 拾取笛卡尔坐标
                // let cartesian3 = this.viewer.scene.pickPosition(evt.position);
                // if (!cartesian3) {
                //     let ray = this.viewer.camera.getPickRay(evt.position);
                //     cartesian3 = this.viewer.scene.globe.pick(ray, this.viewer.scene);
                // }
                let cartesian3 = this.useGetCartesian3(evt.position);
                // 拾取点位异常
                if (!cartesian3) return {error: '拾取点位异常'};
                // 开始绘制面要素
                if (polygonPositions.length === 0) {
                    polygonPositions.push(cartesian3.clone());
                    polygonPositions.push(cartesian3)
                } else {
                    polygonPositions.push(cartesian3)
                }
            } catch (e) {
                console.error(e);
                this.DetachEvent();
            }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        // 鼠标移动事件
        this.drawMapHandler.setInputAction((evt: any) => {
            try {
                let cartesian3 = this.useGetCartesian3(evt.endPosition);
                if (!cartesian3) return { error: '拾取点位异常'};
                // 是否初始创建面要素
                if(polygonPositions.length === 2) {
                    if (!Cesium.defined(polygon)) {
                        polygon = this.useCreatePolyhedron(polygonPositions, name, showName, showMeasure);
                        // this.primitives.push(polygon.id);
                        Entities.push(polygon);
                    }
                }
                polygonPositions.pop();
                polygonPositions.push(cartesian3);
                // 面要素是否存在
                if (polygon) {}
            } catch (e) {
                console.error(e);
                this.DetachEvent();
            }
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        // 右击事件
        this.drawMapHandler.setInputAction((evt: any) => {
            this.DetachEvent();
            resultCallBack(polygon.id, 'polyhedron');

            let measureLabel = this.useCreateLabel(polygonPositions, 'polygon', showMeasure);
            this.useSaveTextLabel(polygon.id, measureLabel, Draw.TYPE.POLYGON);
            measureLabel.label.text = this.useFormatUnit(measureLabel.description, areaUnit);

            let heightLabel = this.useCreateLabel(polygonPositions, Draw.TYPE.Polyhedron, showMeasure);
            // @ts-ignore
            // heightLabel.label.text = polygon.polygon.extrudedHeight + '米';
            heightLabel.label.text = 10 + '米';
            this.useSaveTextLabel(polygon.id, heightLabel, Draw.TYPE.Polyhedron);
            // AreaMeasureLabelEntities.push(measureLabel);
        }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    }

    useLocateById(itemKey: string) {
        // const entity = Entities.find(item => item && item.id === itemKey);
        const entity = this.viewer.entities.getById(itemKey);
        // @ts-ignore
        if (entity.polyline) {
            // 获取线要素的经纬度视角范围
            let extent = this.useGetPolylineExtent(entity);
            // 创建一个cesium的矩形视角
            // @ts-ignore
            let rectangleExtent = new Cesium.Rectangle.fromDegrees(extent.xmin, extent.ymin, extent.xmax, extent.ymax);
            this.viewer.camera.flyTo({
                destination: rectangleExtent,
                duration: 0
            });
        } else {
            let feature = Entities.find(item => item.id === itemKey);
            this.viewer.zoomTo(feature);
        }

        // const entity = this.viewer.entities.getById(itemKey);
        // if(entity.polyline){
        //     // 获取线要素的经纬度视角范围
        //     let extent = this.useGetPolylineExtent(entity);
        //     // 创建一个cesium的矩形视角
        //     if(extent) {
        //         // @ts-ignore
        //         let rectangleExtent = new Cesium.Rectangle.fromDegrees(extent.xmin, extent.ymin, extent.xmax, extent.ymax);
        //         this.viewer.camera.flyTo({
        //             destination: rectangleExtent,
        //             duration: 0
        //         })
        //     }
        // } else if(entity.position){
        //     this.viewer.camera.flyTo({
        //         destination: entity.position._value,
        //         duration: 0
        //     })
        // }
    }

    private useCreateLabel(positions: any, type:string, showMeasure: boolean, float: boolean = false) {
        const that = this;
        if(type === 'point'){
            return this.viewer.entities.add({
                position: positions,
                label: {
                    show: showMeasure,
                    clampToGround: true,
                    fillColor: Cesium.Color.fromCssColorString('white'),
                    text: '',
                    font: '24px MicroSoft YaHei',
                    // eyeOffset: new Cesium.Cartesian3(100, -100, -1000),
                    eyeOffset: new Cesium.Cartesian3(0, 0, 0),
                    scaleByDistance: new Cesium.NearFarScalar(10000, 1, 100000, 0),
                    heightReference: HeightReference.CLAMP_TO_GROUND,
                    disableDepthTestDistance: Number.POSITIVE_INFINITY
                    // backgroundColor: '',
                    // showBackground: ''
                }
            })
        }
        // 线要素
        if (type === 'polyline') {
            return this.viewer.entities.add({
                position: new Cesium.CallbackProperty(function () {
                    return Cesium.BoundingSphere.fromPoints(positions).center;
                }, false),
                label: new Cesium.LabelGraphics({
                    // @ts-ignore
                    text: this.useFormatLengthUnit(this.useGetMeasureDistanceFromArray(positions)),
                    show: showMeasure,
                    eyeOffset: new Cesium.Cartesian3(0.0, 0, -10000),
                    scaleByDistance: new Cesium.NearFarScalar(10000, 1, 100000, 0),
                    font: '40px'
                }),
                description: this.useGetMeasureDistanceFromArray(positions)
            })
        }
        // 面要素
        if (type === Draw.TYPE.POLYGON) {
            return this.viewer.entities.add({
                position: new Cesium.CallbackProperty(function () {
                    return Cesium.BoundingSphere.fromPoints(positions).center;
                    // return positions[positions.length - 1];
                }, false),
                label: new Cesium.LabelGraphics({
                    // text: this.useFormatAreaUnit(this.useGetArea(positions)),
                    text: '',
                    show: showMeasure,
                    font: '24px MicroSoft YaHei',
                    eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),
                    fillColor: Cesium.Color.fromCssColorString('white'),
                    scaleByDistance: new Cesium.NearFarScalar(10000, 1, 100000, 0),
                    disableDepthTestDistance: Number.POSITIVE_INFINITY,
                    // 标签贴地
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    // 基于原点水平居中
                    pixelOffset: new Cesium.Cartesian2(0, 12),
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin: Cesium.VerticalOrigin.TOP,
                }),
                description: this.useGetArea(positions),
            })
        }
        // 矩形
        if (type === Draw.TYPE.RECTANGLE) {
            return this.viewer.entities.add({
                position: new Cesium.CallbackProperty(function () {
                    return Cesium.BoundingSphere.fromPoints(Cesium.Cartesian3.fromDegreesArray(positions)).center;
                    // let cartesian3Positions = Cesium.Cartesian3.fromDegreesArray(positions);
                    // return cartesian3Positions[cartesian3Positions.length - 2]
                }, false),
                label: new Cesium.LabelGraphics({
                    text: '',
                    show: showMeasure,
                    font: '24px MicroSoft YaHei',
                    fillColor: Cesium.Color.fromCssColorString('white'),
                    eyeOffset: new Cesium.Cartesian3(0.0, 0, 0),
                    // 地形遮挡
                    disableDepthTestDistance: Number.POSITIVE_INFINITY,
                    scaleByDistance: new Cesium.NearFarScalar(10000, 1, 100000, 0),
                    // 贴地
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    // 原点
                    pixelOffset: new Cesium.Cartesian2(0, 12),
                    // 水平居中
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    // 垂直基于顶端
                    verticalOrigin: Cesium.VerticalOrigin.TOP,
                }),
                description: this.useGetArea(Cesium.Cartesian3.fromDegreesArray(positions)),
            })
        }
        if (type === Draw.TYPE.CIRCLE) {
            return this.viewer.entities.add({
                position: new Cesium.CallbackProperty(function () {
                    return positions[0]
                }, false),
                label: new Cesium.LabelGraphics({
                    // text: this.useFormatAreaUnit(this.useGetCircleArea(positions)),
                    text: '',
                    show: showMeasure,
                    font: '24px MicroSoft YaHei',
                    fillColor: Cesium.Color.fromCssColorString('white'),
                    eyeOffset: new Cesium.Cartesian3(0.0, 0, 0),
                    disableDepthTestDistance: Number.POSITIVE_INFINITY,
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    // 原点
                    pixelOffset: new Cesium.Cartesian2(0, 14),
                    scaleByDistance: new Cesium.NearFarScalar(10000, 1, 100000, 0),
                    // 水平
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    // 垂直
                    verticalOrigin: Cesium.VerticalOrigin.TOP
                }),
                description: this.useGetCircleArea(positions),
            })
        }
        // 多面体
        if (type === Draw.TYPE.Polyhedron){
            return this.viewer.entities.add({
                // position: Cesium.BoundingSphere.fromPoints(positions).center,
                position: positions[0],
                label: {
                    show: showMeasure,
                    clampToGround: true,
                    fillColor: Cesium.Color.fromCssColorString('white'),
                    text: '',
                    font: '24px MicroSoft YaHei',
                    // eyeOffset: new Cesium.Cartesian3(100, -400, -1000),
                    eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),
                    disableDepthTestDistance: Number.POSITIVE_INFINITY,
                    // 标签贴地
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    // 基于原点水平居中
                    pixelOffset: new Cesium.Cartesian2(0, 12),
                    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                    verticalOrigin: Cesium.VerticalOrigin.TOP,
                    // backgroundColor: '',
                    // showBackground: ''
                }
            })
        }
    }
    // 获取笛卡尔数组的空间距离
    private useGetMeasureDistanceFromArray(cartesian3sArray:Array<any>) {
        // 存储计算距离的结果 用于返回
        let distance = 0;
        let cartesian;
        let arrayLength = cartesian3sArray.length;
        // TODO 这里之后可以补一个抛出错误
        if (arrayLength < 2) return;
        // 遍历数组计算笛卡尔坐标数组的空间距离
        for (let i = 0; i < arrayLength - 1; i++) {
            distance += this.useMeasureDistance(cartesian3sArray[i], cartesian3sArray[i + 1]);
        }
        return distance;
    }

    private useMeasureDistance(cartesian3x: any, cartesian3y: any) {
        let distance = 0;
        if (!cartesian3x || !cartesian3y) return distance;
        distance = Cesium.Cartesian3.distance(cartesian3x, cartesian3y);
        return distance
    }
    //计算多边形面积
    useGetArea(positions:Array<Cesium.Cartesian3>) {
        let result = 0
        if (!Array.isArray(positions)) {
            console.log('不是数组');
            return result
        }

        //创建一个geometry
        let geometry = Cesium.CoplanarPolygonGeometry.createGeometry(
          Cesium.CoplanarPolygonGeometry.fromPositions({
              positions: positions,
              vertexFormat: Cesium.VertexFormat.POSITION_ONLY
          })
        )

        if (!geometry) {
            console.log('不是geometry');
            return result
        }

        //顶点坐标数组p;
        let flatPositions = geometry.attributes.position.values
        // console.log(flatPositions);

        //确定geometry的基本体的索引，也就是组成其的三角形的索引，每三个为一组，组成一个三角形
        let indices = geometry.indices
        // console.log(indices);


        // console.log("移动索引", indices)
        //计算三角形面积，最后加在一起
        for (let i = 0; i < indices.length; i += 3) {
            let p0 = Cesium.Cartesian3.unpack(
              flatPositions,
              indices[i] * 3,
              new Cesium.Cartesian3()
            )
            // console.log(p0);

            let p1 = Cesium.Cartesian3.unpack(
              flatPositions,
              indices[i + 1] * 3,
              new Cesium.Cartesian3()
            )
            // console.log(p1);
            let p2 = Cesium.Cartesian3.unpack(
              flatPositions,
              indices[i + 2] * 3,
              new Cesium.Cartesian3()
            )
            // console.log(p2);
            result += this.triangleArea(p0, p1, p2)
            // console.log("移动result", result)

        }
        return result
    }
//计算三角形面积
    triangleArea(p0, p1, p2) {
        let v0 = Cesium.Cartesian3.subtract(p0, p1, new Cesium.Cartesian3())
        let v1 = Cesium.Cartesian3.subtract(p2, p1, new Cesium.Cartesian3())
        let cross = Cesium.Cartesian3.cross(v0, v1,v0);
        return Cesium.Cartesian3.magnitude(cross) * 0.5
    }

    // private useGetArea(positions:Array<Cartesian3>) {
    //     let area = 0;
    //     for (let i = 0; i < positions.length; i++) {
    //         let j = (i + 1) % positions.length;
    //         area += positions[i].x * positions[j].y;
    //         area -= positions[i].y * positions[j].x;
    //     }
    //     area /= 2;
    //     return Math.abs(area)
    // }

    private useGetRectangleArea(positions: Array<any>) {
        // TODO 矩形的面积计算
        return 0
    }
    private useGetCircleArea(positions: Array<Cartesian3>) {
        let area = (this.PI * this.useMeasureDistance(positions[0], positions[1]) ** 2);
        return area
    }
    // 删除所有的要素
    useRemoveAllFeatures() {
        Entities.forEach(item => item && this.viewer.entities.remove(item));
        // LengthMeasureLabelEntities.forEach(item => item && this.viewer.entities.remove(item));
        // AreaMeasureLabelEntities.forEach(item => item && this.viewer.entities.remove(item));
        for(let arr of Object.values(LengthMeasureLabelEntities)){
            // @ts-ignore
            arr.forEach(item => item && this.viewer.entities.remove(item))
        }
        for(let arr of Object.values(AreaLabelEntities)){
            // @ts-ignore
            arr.forEach(item => item && this.viewer.entities.remove(item))
        }
        for(let arr of Object.values(HeightLabelEntities)){
            // @ts-ignore
            arr.forEach(item => item && this.viewer.entities.remove(item))
        }
    }

    /**
     * 显示要素的量算值
     * @param value
     */
    useSetMeasureValue(value: boolean) {
        // 遍历取所有线要素的textLabel设置show为true
        for(let arr of Object.values(LengthMeasureLabelEntities)){
            // @ts-ignore
            arr.forEach(item => item.label.show = value);
        }
        for(let arr of Object.values(AreaLabelEntities)){
            // @ts-ignore
            arr.forEach(item => item.label.show = value);
        }
        for(let arr of Object.values(HeightLabelEntities)){
            // @ts-ignore
            arr.forEach(item => item.label.show = value);
        }
        // // @ts-ignore
        // AreaMeasureLabelEntities.forEach(item => item.label && (item.label.show.setValue(value)));
    }

    useSetFeaturesName(value: boolean) {
        // @ts-ignore
        Entities.forEach(item => item && item.label && (item.label.show = value))
    }

    useChangeAreaUnit(unit: string = '平方米') {
        this.AreaUnit = unit;
        if (unit === '平方米') {
            // @ts-ignore
            AreaMeasureLabelEntities.forEach(item => item && item.label && (item.label.text = Number(item.description).toFixed(2) + unit))
        } else if (unit === '平方公里') {
            // @ts-ignore
            AreaMeasureLabelEntities.forEach(item => item && item.label && (item.label.text = (item.description / 1000000).toFixed(2) + unit))
        } else if (unit === '公顷') {
            // @ts-ignore
            AreaMeasureLabelEntities.forEach(item => item && item.label && (item.label.text = (item.description / 10000).toFixed(2) + unit))
        } else if (unit === '亩') {
            // @ts-ignore
            AreaMeasureLabelEntities.forEach(item => item && item.label && (item.label.text = ((item.description * 15 / 1000).toFixed(2)  + unit)))
        }
    }

    private useFormatAreaUnit(areaValue: number) {
        if (this.AreaUnit === '平方米') {
            return areaValue.toFixed(2) + this.AreaUnit
        } else if (this.AreaUnit === '平方公里') {
            return (areaValue / 1000000).toFixed(2) + this.AreaUnit
        } else if (this.AreaUnit === '公顷') {
            return (areaValue / 10000).toFixed(2) + this.AreaUnit
        } else if (this.AreaUnit === '亩') {
            return (areaValue * 15 / 1000).toFixed(2) + this.AreaUnit
        }
    }

    private useFormatLengthUnit(lengthValue: number) {
        if (this.LengthUnit === '米') {
            return lengthValue.toFixed(2) + this.LengthUnit
        } else if (this.LengthUnit === '千米') {
            return (lengthValue / 1000).toFixed(2) + this.LengthUnit
        }
    }

    // 获取线要素经纬度视角范围
    private useGetPolylineExtent(entity: Cesium.Entity | undefined) {
        // @ts-ignore
        let positions = entity.polyline.positions.getValue();
        let cartographic_array: Cesium.Cartographic[] = [];
        let degrees: { lat: number; lng: number; }[] = [];
        // 获取每一个定位的弧度
        // @ts-ignore
        positions.forEach(item => {
            cartographic_array.push(Cesium.Cartographic.fromCartesian(item))
        });
        // 获取每一个点位的经纬度
        cartographic_array.forEach(cartographic => {
            // 弧度转经纬度
            // 维度
            let lat = Cesium.Math.toDegrees(cartographic.latitude);
            // 经度
            let lng = Cesium.Math.toDegrees(cartographic.longitude);
            degrees.push({lat: lat, lng: lng});
        });
        let xmin, ymin, xmax, ymax;
        // 循环经纬度获取最大最小值
        for(let i = 0; i < degrees.length; i++) {
            if (i === 0) {
                xmin = degrees[i].lng;
                xmax = degrees[i].lng;
                ymin = degrees[i].lat;
                ymax = degrees[i].lat;
            }
            // @ts-ignore
            if (degrees[i].lng < xmin) {
               xmin = degrees[i].lng
            }
            // @ts-ignore
            if (degrees[i].lng > xmax) {
                xmax = degrees[i].lng
            }
            // @ts-ignore
            if (degrees[i].lat < ymin) {
                ymin = degrees[i].lat
            }
            // @ts-ignore
            if (degrees[i].lat > ymax) {
                ymax = degrees[i].lat
            }
        }
        return {xmin: xmin, ymin: ymin, xmax: xmax, ymax: ymax};
    }

    // 通过要素的id修改要素的name
    useChangeFeatureNameById(itemKey: string, name: any) {
        // const entity = Entities.find(item => item && item.id === itemKey);
        // // 修改要素name
        // entity && entity.label && (entity.label.text = name);
        let entity = this.viewer.entities.getById(itemKey);
        entity.label.text = name;
    }

    useFormatUnit(value: number, unitType: string) {
        if(!value) return;
        let res;
        switch (unitType) {
            case Draw.UNIT.DIS.M:
                res = Number(value).toFixed(2) + Draw.UNIT.DIS.M;
                break;
            case Draw.UNIT.DIS.KM:
                res = (value / 1000).toFixed(2) + Draw.UNIT.DIS.KM;
                break;
            case Draw.UNIT.AREA.SM:
                res = Number(value).toFixed(2) + Draw.UNIT.AREA.SM;
                break;
            case Draw.UNIT.AREA.SKM:
                res = (value / 1000000).toFixed(2) + Draw.UNIT.AREA.SKM;
                break;
            case Draw.UNIT.AREA.ACRES:
                res = (value * 15 / 1000).toFixed(2) + Draw.UNIT.AREA.ACRES;
                break;
            case Draw.UNIT.AREA.HECTARE:
                res = (value / 10000).toFixed(2) + Draw.UNIT.AREA.HECTARE;
                break;
            default:
                res = 'NaN';
                break;
        }
        return res;
    }

    private useSaveTextLabel(id: string, textLabel: Cesium.Entity, type: string) {
        if(type === Draw.TYPE.POLYLINE){
            // @ts-ignore
            if(!LengthMeasureLabelEntities[id]){
                // @ts-ignore
                LengthMeasureLabelEntities[id] = [];
                // @ts-ignore
                LengthMeasureLabelEntities[id].push(textLabel);
            } else {
                // @ts-ignore
                LengthMeasureLabelEntities[id].push(textLabel);
            }
        } else if (type === Draw.TYPE.POLYGON){
            // @ts-ignore
            if(!AreaLabelEntities[id]){
                // @ts-ignore
                AreaLabelEntities[id] = [];
                // @ts-ignore
                AreaLabelEntities[id].push(textLabel);
            }else {
                // @ts-ignore
                AreaLabelEntities[id].push(textLabel);
            }
        } else if(type === Draw.TYPE.Polyhedron){
            // @ts-ignore
            if(!HeightLabelEntities[id]){
                // @ts-ignore
                HeightLabelEntities[id] = [];
                // @ts-ignore
                HeightLabelEntities[id].push(textLabel);
            }else {
                // @ts-ignore
                HeightLabelEntities[id].push(textLabel);
            }
        }
    }

    /**
     * 根据id移除要素
     * @param itemKey
     */
    useRemoveFeatureById(itemKey: string){
        // 移除要素
        this.viewer.entities.removeById(itemKey);
        // 移除要素相关的 example 线要素的距离量算标签
        // @ts-ignore
        if(LengthMeasureLabelEntities[itemKey]){
            // @ts-ignore
            LengthMeasureLabelEntities[itemKey].forEach(item => {
                this.viewer.entities.removeById(item.id);
            })
        }
        // @ts-ignore
        if(AreaLabelEntities[itemKey]){
            // @ts-ignore
            AreaLabelEntities[itemKey].forEach(item => {
                this.viewer.entities.removeById(item.id);
            })
        }
        // @ts-ignore
        if(HeightLabelEntities[itemKey]){
            // @ts-ignore
            HeightLabelEntities[itemKey].forEach(item => {
                this.viewer.entities.removeById(item.id);
            })
        }
    }

    /**
     * 长度单位改变事件
     * @param unitValue
     */
    useChangeLengthUnit(unitValue: any) {
        //遍历所有的线要素和标签要素 改变单位
        for(let arr of Object.values(LengthMeasureLabelEntities)){
            // @ts-ignore
            arr.forEach(item => {
                item.label.text = this.useFormatUnit(Number(item.description), unitValue)
            })
        }
    }

    /**
     * 新的面积单位改变事件
     * @param unit 单位值
     */
    useChangeAreaUnitNew(unitValue: any) {
        // 遍历所有的面要素及他们的标签要素
        for(let arr of Object.values(AreaLabelEntities)){
            // @ts-ignore
            arr.forEach(item => {
                item.label.text = this.useFormatUnit(Number(item.description), unitValue)
            })
        }
    }

    // 设置多面体的高度
    setPolyhedronHeight(itemKey: string, height: any) {
        let feature = this.viewer.entities.getById(itemKey);
        // feature.polygon.extrudedHeight.setValue(Number(height));
        feature.polygon.extrudedHeight = Number(height);
        // 改变标签的值
        // @ts-ignore
        HeightLabelEntities[itemKey].forEach(item => {
            item.label.text = height + '米';
        })
    }

    // 清空绘制要素
    useClearDrawFeatures() {
        Entities.forEach(item => this.viewer.entities.remove(item))
        // 量算

    }

    /****          *****useLoad-前缀为获取在线收藏要素的接口*****                     ***/

    useLoadPoint(data: { name: any; positions: any[]; id: any }, option?: any) {
        this.useGeneratePoint(data, option);
    }

    private useGeneratePoint(data: { name: any; positions: any[]; id: any }, option?: any) {
        let point = new Cesium.Entity({
            position: Cesium.Cartesian3.fromDegrees(data.positions[0], data.positions[1]),
            id: data.id,
            point: {
                // 颜色
                color: option ? Cesium.Color.fromBytes(
                  option.fillColor[0],
                  option.fillColor[1],
                  option.fillColor[2],
                  option.fillColor[3] > 1 ? option.fillColor[3] : option.fillColor[3] *255
                ): Cesium.Color.TRANSPARENT,
                // color: option ? (option:any)=>{
                //     if(Array.isArray(option.fillColor)){
                //         return Cesium.Color.fromBytes(
                //           option.fillColor[0],
                //           option.fillColor[1],
                //           option.fillColor[2],
                //           option.fillColor[3]
                //         )
                //     }else {
                //         return Cesium.Color.fromCssColorString(option.fillColor)
                //     }
                // } : Cesium.Color.TRANSPARENT,
                // 贴地
                // @ts-ignore
                clampToGround: true,
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
                // 大小
                pixelSize: option? option.size:10,
                outlineColor: option? Cesium.Color.fromBytes(
                  option.outlineColor[0],
                  option.outlineColor[1],
                  option.outlineColor[2],
                  option.outlineColor[3] > 1 ? option.outlineColor[3] : option.outlineColor[3] *255
                ) : undefined,
                // outlineColor: option ? (option:any)=>{
                //     if(Array.isArray(option.fillColor)){
                //         return Cesium.Color.fromBytes(
                //           option.outlineColor[0],
                //           option.outlineColor[1],
                //           option.outlineColor[2],
                //           option.outlineColor[3]
                //         )
                //     }else {
                //         return Cesium.Color.fromCssColorString(option.fillColor)
                //     }
                // } : Cesium.Color.fromCssColorString('#409eff'),
                outlineWidth: option ? option.width : undefined
            },
            label: new Cesium.LabelGraphics({
                // text: this.useFormatAreaUnit(this.useGetArea(positions)),
                show:true,
                text: data.name,
                font: '24px MicroSoft YaHei',
                eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                // 标签贴地
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                // 基于原点水平居中
                pixelOffset: new Cesium.Cartesian2(0, 10),
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.TOP,
            }),
        });
        this.viewer.entities.add(point);
        Entities.push(point);
        // this.viewer.zoomTo(point);
    }

    useLoadPolyline(postPolylineData: { name: string; positions: any[]; id: string,measure:string }, polylineOption?:any) {
        this.useGeneratePolyline(postPolylineData, polylineOption);
    }

    private useGeneratePolyline(postPolylineData: { name: any; positions: any[]; id: any,measure:string }, polylineOption?:any) {
        let positions = Cesium.Cartesian3.fromDegreesArray(postPolylineData.positions);
        let measureLabel = new Cesium.Entity({
            // @ts-ignore
            // id: polygonData.id,
            name: postPolylineData.name,
            // @ts-ignore
            position: new Cesium.CallbackProperty(function () {
                return Cesium.BoundingSphere.fromPoints(positions).center;
            }, false),
            label: new Cesium.LabelGraphics({
                // text: this.useFormatAreaUnit(this.useGetArea(positions)),
                show:true,
                text: Number(postPolylineData.measure).toFixed(2) + "米",
                font: '24px MicroSoft YaHei',
                eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),
                fillColor: Cesium.Color.fromCssColorString('white'),
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                // 标签贴地
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                // 基于原点水平居中
                pixelOffset: new Cesium.Cartesian2(0, 12),
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.TOP,
            }),
            description: postPolylineData.measure
        })
        let polyline = new Cesium.Entity({
            id: postPolylineData.id,
            name: postPolylineData.name,
            // @ts-ignore
            position: new Cesium.CallbackProperty(function () {
                return Cesium.BoundingSphere.fromPoints(positions).center;
            }, false),
            polyline: new Cesium.PolylineGraphics({
                positions: new Cesium.CallbackProperty(function () {
                    return positions
                }, false),
                show: true,
                // material: polylineOption ? (polylineOption:any)=>{
                //     if(Array.isArray(polylineOption.fillColor)){
                //         return Cesium.Color.fromBytes(
                //           polylineOption.fillColor[0],
                //           polylineOption.fillColor[1],
                //           polylineOption.fillColor[2],
                //           polylineOption.fillColor[3]
                //         )
                //     }else {
                //         return Cesium.Color.fromCssColorString(polylineOption.fillColor)
                //     }
                // } : Cesium.Color.fromCssColorString('#409eff'),
                material: polylineOption ? Cesium.Color.fromBytes(
                  polylineOption.fillColor[0],
                  polylineOption.fillColor[1],
                  polylineOption.fillColor[2],
                  polylineOption.fillColor[3] > 1 ? polylineOption.fillColor[3] : polylineOption.fillColor[3] *255
                ): Cesium.Color.fromCssColorString('#409eff'),
                width: polylineOption?.width || 5,
                clampToGround: true,
                classificationType: Cesium.ClassificationType.BOTH,
            }),
            label: new Cesium.LabelGraphics({
                text: postPolylineData.name,
                font: '24px MicroSoft YaHei',
                fillColor: Cesium.Color.fromCssColorString('white'),
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            }),
        });
        this.viewer.entities.add(measureLabel);
        this.useSaveTextLabel(polyline.id, measureLabel, Draw.TYPE.POLYLINE);
        this.viewer.entities.add(polyline);
        Entities.push(polyline);
    }

    useLoadPolygon(polygonData: { name: string; positions: any[]; id: string, measure:string }, polygonOption?: any) {
        this.useGeneratePolygon(polygonData, polygonOption);
    }

    private useGeneratePolygon(polygonData: { name: any; positions: any[]; id: any,measure:string }, polygonOption?: any) {
        let positions = Cesium.Cartesian3.fromDegreesArray(polygonData.positions);
        let measureLabel = new Cesium.Entity({
            // @ts-ignore
            // id: polygonData.id,
            name: polygonData.name,
            // @ts-ignore
            position: new Cesium.CallbackProperty(function () {
                return Cesium.BoundingSphere.fromPoints(positions).center;
            }, false),
            label: new Cesium.LabelGraphics({
                // text: this.useFormatAreaUnit(this.useGetArea(positions)),
                show:true,
                text: Number(polygonData.measure).toFixed(2) + "平方米",
                font: '24px MicroSoft YaHei',
                eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),
                fillColor: Cesium.Color.fromCssColorString('white'),
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                // 标签贴地
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                // 基于原点水平居中
                pixelOffset: new Cesium.Cartesian2(0, 12),
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.TOP,
            }),
            description: polygonData.measure
        })
        let polygon = new Cesium.Entity({
            id: polygonData.id,
            name: polygonData.name,
            // @ts-ignore
            position: new Cesium.CallbackProperty(function () {
                return Cesium.BoundingSphere.fromPoints(positions).center;
            }, false),
            polygon: new Cesium.PolygonGraphics({
                hierarchy: new Cesium.CallbackProperty(function () {
                    return new Cesium.PolygonHierarchy(positions)
                }, false),
                // clampToGround: true,
                material: polygonOption ? Cesium.Color.fromBytes(
                  polygonOption.fillColor[0],
                  polygonOption.fillColor[1],
                  polygonOption.fillColor[2],
                  polygonOption.fillColor[3] > 1 ? polygonOption.fillColor[3] : polygonOption.fillColor[3] *255
                ): Cesium.Color.WHITESMOKE.withAlpha(0.3),
                // material: polygonOption ? (polygonOption:any)=>{
                //     if(Array.isArray(polygonOption.fillColor)){
                //         return Cesium.Color.fromBytes(
                //           polygonOption.fillColor[0],
                //           polygonOption.fillColor[1],
                //           polygonOption.fillColor[2],
                //           polygonOption.fillColor[3]
                //         )
                //     }else {
                //         return Cesium.Color.fromCssColorString(polygonOption.fillColor)
                //     }
                // } : Cesium.Color.WHITESMOKE.withAlpha(0.3),
                // disableDepthTestDistance: Number.POSITIVE_INFINITY,
                show: true,
                fill: true,
                outline: true,
                // outlineColor: new Cesium.Color(64, 133, 235),
                // outlineColor: Cesium.Color.YELLOW,
                // outlineColor: new Cesium.Color.fromCssColorString(outlineColor),
                outlineWidth: 1
            }),
            polyline: new Cesium.PolylineGraphics({
                positions: new Cesium.CallbackProperty(function () {
                    return positions
                }, false),
                show: true,
                // material: polygonOption ? (polygonOption:any)=>{
                //     if(Array.isArray(polygonOption.fillColor)){
                //         return Cesium.Color.fromBytes(
                //           polygonOption.fillColor[0],
                //           polygonOption.fillColor[1],
                //           polygonOption.fillColor[2],
                //           polygonOption.fillColor[3]
                //         )
                //     }else {
                //         return Cesium.Color.fromCssColorString(polygonOption.fillColor)
                //     }
                // } : Cesium.Color.fromCssColorString('#409eff'),
                material: polygonOption ? Cesium.Color.fromBytes(
                  polygonOption.outlineColor[0],
                    polygonOption.outlineColor[1],
                    polygonOption.outlineColor[2],
                    polygonOption.outlineColor[3] > 1 ? polygonOption.outlineColor[3] : polygonOption.outlineColor[3] *255
                  ): Cesium.Color.fromCssColorString('#409eff'),
                width: polygonOption?.width || 5,
                clampToGround: true,
                classificationType: Cesium.ClassificationType.BOTH,
            }),
            label: new Cesium.LabelGraphics({
                text: polygonData.name,
                font: '24px MicroSoft YaHei',
                fillColor: Cesium.Color.fromCssColorString('white'),
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            }),
        });
        // this.myEntityCollection.add(measureLabel);
        // let measureLabel = this.useCreateLabel(positions, Draw.TYPE.POLYGON, true);
        this.viewer.entities.add(measureLabel);
        this.useSaveTextLabel(polygon.id, measureLabel, Draw.TYPE.POLYGON);
        this.viewer.entities.add(polygon);
        Entities.push(polygon);
    }


    useLoadPolyhedron(polyhedronData: { name: string; positions: any[]; id: string, measure:string, extrudedHeight:number }, polyhedronOption?: any) {
        this.useGeneratePolyhedron(polyhedronData, polyhedronOption);
    }

    private useGeneratePolyhedron(polyhedronData: { name: any; positions: any[]; id: any,measure:string, extrudedHeight:number }, polyhedronOption?: any) {
        let positions = Cesium.Cartesian3.fromDegreesArray(polyhedronData.positions);
        let measureLabel = new Cesium.Entity({
            // @ts-ignore
            // id: polygonData.id,
            name: polyhedronData.name,
            // @ts-ignore
            position: new Cesium.CallbackProperty(function () {
                return Cesium.BoundingSphere.fromPoints(positions).center;
            }, false),
            label: new Cesium.LabelGraphics({
                // text: this.useFormatAreaUnit(this.useGetArea(positions)),
                show:true,
                text: Number(polyhedronData.measure).toFixed(2) + "平方米",
                font: '24px MicroSoft YaHei',
                eyeOffset: new Cesium.Cartesian3(0.0, 0.0, 0.0),
                fillColor: Cesium.Color.fromCssColorString('white'),
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                // 标签贴地
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                // 基于原点水平居中
                pixelOffset: new Cesium.Cartesian2(0, 12),
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.TOP,
            }),
            description: polyhedronData.measure
        })
        let polyhedron = new Cesium.Entity({
            id: polyhedronData.id,
            name: polyhedronData.name,
            // @ts-ignore
            position: new Cesium.CallbackProperty(function () {
                return Cesium.BoundingSphere.fromPoints(positions).center;
            }, false),
            polygon: new Cesium.PolygonGraphics({
                hierarchy: new Cesium.CallbackProperty(function () {
                    return new Cesium.PolygonHierarchy(positions)
                }, false),
                // clampToGround: true,
                material: polyhedronOption ? Cesium.Color.fromBytes(
                  polyhedronOption.fillColor[0],
                  polyhedronOption.fillColor[1],
                  polyhedronOption.fillColor[2],
                  polyhedronOption.fillColor[3]
                ): Cesium.Color.WHITESMOKE.withAlpha(0.3),
                // disableDepthTestDistance: Number.POSITIVE_INFINITY,
                show: true,
                fill: true,
                outline: true,
                arcType: Cesium.ArcType.RHUMB,
                closeBottom:true,
                heightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
                // height:0,
                // extrudedHeightReference:Cesium.HeightReference.CLAMP_TO_GROUND,
                // outlineColor: new Cesium.Color(64, 133, 235),
                // outlineColor: Cesium.Color.YELLOW,
                // outlineColor: new Cesium.Color.fromCssColorString(outlineColor),
                outlineWidth: 1,
                extrudedHeight: polyhedronData.extrudedHeight || 0
            }),
            polyline: new Cesium.PolylineGraphics({
                positions: new Cesium.CallbackProperty(function () {
                    return [...positions,positions[0]]
                }, false),
                show: true,
                // material: polyhedronOption ? Cesium.Color.fromBytes(
                //   polyhedronOption.outlineColor[0],
                //   polyhedronOption.outlineColor[1],
                //   polyhedronOption.outlineColor[2],
                //   polyhedronOption.outlineColor[3]
                // ): Cesium.Color.fromCssColorString('#409eff'),
                material: Cesium.Color.fromCssColorString('#409eff'),
                // width: polyhedronOption?.width || 10,
                width: 5,
                clampToGround: true,
                classificationType: Cesium.ClassificationType.BOTH,
            }),
            label: new Cesium.LabelGraphics({
                text: polyhedronData.name,
                font: '24px MicroSoft YaHei',
                fillColor: Cesium.Color.fromCssColorString('white'),
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
            }),
        });
        let heightLabel = this.useCreateLabel(positions, Draw.TYPE.Polyhedron,true);
        heightLabel.label.text = polyhedronData.extrudedHeight + "米";
        this.useSaveTextLabel(polyhedron.id, heightLabel, Draw.TYPE.Polyhedron);
        // this.myEntityCollection.add(measureLabel);
        // let measureLabel = this.useCreateLabel(positions, Draw.TYPE.POLYGON, true);
        this.viewer.entities.add(measureLabel);
        this.useSaveTextLabel(polyhedron.id, measureLabel, Draw.TYPE.POLYGON);
        this.viewer.entities.add(polyhedron);
        Entities.push(polyhedron);
    }

}


